package com.qf.openapi.zuul.consumer;

import com.qf.openapi.zuul.utils.ZuulLocalCache;
import com.qf.qfsy.mqbean.ApimappingMqBean;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;

@Component
@Slf4j
public class ApiMappingConsumer {

    @RabbitListener(queues = "openapi-apimapping-queue")
    public void getMsg(ApimappingMqBean mqBean, Message message, Channel channel) throws IOException {
        log.info("网关接受到路由更改的消息={}",mqBean);

        // 根据消息对象更新网关的本地缓存
        String type = mqBean.getType();
        String key = mqBean.getKey();
        HashMap data = mqBean.getData();
        if (type.equals("add")){
            ZuulLocalCache.routingCache.put(key,data);
            log.info("添加路由信息到本地缓存:{}",data);
        }else if (type.equals("update")){

            Integer state = (Integer) data.get("state");
            if (state==0){ // 路由有效
                ZuulLocalCache.routingCache.put(key,data);
                log.info("修改路由信息到本地缓存:{}",data);
            }else {
                ZuulLocalCache.routingCache.remove(key);
                log.info("删除路由信息到本地缓存:{}",data);
            }

        }else if (type.equals("delete")){
            ZuulLocalCache.routingCache.remove(key);
            log.info("删除路由信息到本地缓存:{}",data);
        }


        // 手动ack
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

}
